/**
 *  GTUG Zaragoza
 *  http://zaragoza.gtugs.org/
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.gtugs.zaragoza.feeds.provider;

import org.gtugs.zaragoza.feeds.FeedEntry;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

/**
 *
 * @author pfraca
 */
public class FeedEntryContentProvider extends ContentProvider {

    private static DatabaseHelper theDatabaseConnection;
    private static UriMatcher sUriMatcher;
    public static final String AUTHORITY = "com.google.provider.gtug";
    private static final String SCHEME = "content://";
    private static final String PATH_NOTE_ID = "/feeds/";
    private static final String PATH_NOTE= "/feeds";

    public static final Uri CONTENT_ID_URI_BASE
            = Uri.parse(SCHEME + AUTHORITY + PATH_NOTE_ID);
    
    public static final Uri CONTENT_URI_BASE
    = Uri.parse(SCHEME + AUTHORITY + PATH_NOTE);

    /*
     * Constants used by the Uri matcher to choose an action based on the pattern
     * of the incoming URI
     */
    // The incoming URI matches the Notes URI pattern
    private static final int FEEDS = 1;

    // The incoming URI matches the Note ID URI pattern
    private static final int FEED = 2;

    static {
        /*
         * Creates and initializes the URI matcher
         */
        // Create a new instance
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        // Add a pattern that routes URIs terminated with "notes" to a NOTES operation
        sUriMatcher.addURI(AUTHORITY, "feeds", FEEDS);

        // Add a pattern that routes URIs terminated with "notes" plus an integer
        // to a note ID operation
        sUriMatcher.addURI(AUTHORITY, "feeds/#", FEED);
    }
    @Override
    public boolean onCreate() {
        theDatabaseConnection = new DatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    	 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
         qb.setTables(FeedEntry.class.getSimpleName());

         /**
          * Choose the projection and adjust the "where" clause based on URI pattern-matching.
          */
         switch (sUriMatcher.match(uri)) {
             // If the incoming URI is for notes, chooses the Notes projection
             case FEEDS:
                 break;

             /* If the incoming URI is for a single note identified by its ID, chooses the
              * feed ID projection, and appends "_ID = <feedID>" to the where clause, so that
              * it selects that single feed
              */
             case FEED:
                qb.appendWhere(
                     FeedEntry._ID +    // the name of the ID column
                     "=" +
                     // the position of the note ID itself in the incoming URI
                     uri.getPathSegments().get(1));
                 break;
         }
         
         String orderBy;
         // If no sort order is specified, uses the default
         if (TextUtils.isEmpty(sortOrder)) {
             orderBy = FeedEntry.UPDATED + " DESC";
         } else {
             // otherwise, uses the incoming sort order
             orderBy = sortOrder;
         }

         // Opens the database object in "read" mode, since no writes need to be done.
         SQLiteDatabase db = theDatabaseConnection.getReadableDatabase();

         /*
          * Performs the query. If no problems occur trying to read the database, then a Cursor
          * object is returned; otherwise, the cursor variable contains null. If no records were
          * selected, then the Cursor object is empty, and Cursor.getCount() returns 0.
          */
         Cursor c = qb.query(
             db,            // The database to query
             projection,    // The columns to return from the query
             selection,     // The columns for the where clause
             selectionArgs, // The values for the where clause
             null,          // don't group the rows
             null,          // don't filter by row groups
             orderBy        // The sort order
         );

         // Tells the Cursor what URI to watch, so it knows when its source data changes
         c.setNotificationUri(getContext().getContentResolver(), uri);
         return c;
    }

    @Override
    public String getType(Uri arg0) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
         // Validates the incoming URI. Only the full provider URI is allowed for inserts.
        if (sUriMatcher.match(uri) != FEEDS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // A map to hold the new record's values.
        ContentValues values;

        // If the incoming values map is not null, uses it for the new values.
        if (initialValues != null) {
            values = new ContentValues(initialValues);

        } else {
            // Otherwise, create a new value map
            values = new ContentValues();
        }

        // Gets the current system time in milliseconds
        Long now = Long.valueOf(System.currentTimeMillis());

       
        // Opens the database object in "write" mode.
        SQLiteDatabase db = theDatabaseConnection.getWritableDatabase();

        // Performs the insert and returns the ID of the new feed.
        long rowId = db.insert(
            FeedEntry.class.getSimpleName(),        // The table to insert into.
            null,                            // A hack, SQLite sets this column value to null
                                             // if values is empty.
            values                           // A map of column names, and the values to insert
                                             // into the columns.
        );

        // If the insert succeeded, the row ID exists.
        if (rowId > 0) {
            // Creates a URI with the feed ID pattern and the new row ID appended to it.
            Uri feedUri = ContentUris.withAppendedId(Uri.parse(SCHEME + AUTHORITY + PATH_NOTE_ID), rowId);

            // Notifies observers registered against this provider that the data changed.
            getContext().getContentResolver().notifyChange(feedUri, null);
            return feedUri;
        }

        // If the insert didn't succeed, then the rowID is <= 0. Throws an exception.
        throw new SQLException("Failed to insert row into " + uri);

    }

    @Override
    public int delete(Uri arg0, String arg1, String[] arg2) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

   
}
